package cn.demoframe.test.frame.service;

import cn.demoframe.test.frame.model.OprLog;
import cn.demoframe.test.model.Message;
import cn.demoframe.test.utils.DateToolkit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Map;

@Aspect
@Component
public class LogAspect {
	
	@Resource
	public OprLogService oprLog;

	@Before("execution(* cn.demoframe..*.controller..*.*(..))")
	public void setReqReachTime(JoinPoint joinPoint) {
		try{
			Object args[] = joinPoint.getArgs();
			HttpServletRequest request = getRequest(args);
			if(request == null) {
				return;
			}

			request.setAttribute("reqReachTime", DateToolkit.getNowString());
		} catch (Exception e) {
			System.out.println("aop log error =========" + e);
		}
	}

	@AfterReturning(returning="rv", pointcut="execution(* cn.demoframe..*.controller..*.*_log(..))")
	public void insertService(JoinPoint joinPoint, Object rv) {
		Object args[] = joinPoint.getArgs();
		HttpServletRequest request = getRequest(args);
		if(request == null) {
			return;
		}

		String reqReachTime = "";
		if(request.getAttribute("reqReachTime") != null){
			reqReachTime = request.getAttribute("reqReachTime").toString();
		}
		String buss = joinPoint.getSignature().getName();
		buss = buss.substring(0, buss.lastIndexOf("_log"));
		OprLog log = new OprLog();
		log.setOpType(buss);
		try {
			if(buss.contains("login")) {
				String res = rv.toString();
				if (res.equals("0")) {
					log.setOpContent("在" + reqReachTime + "登录了系统");
					log.setRetCode("0");
				}  else {
					return;
				}
			} else {
				Message m = (Message) rv;
				log.setRetCode(m.getResult());
				log.setRetMsg(m.getDetail());
				log.setOpContent(getLogContent(joinPoint, request));
			}
			String userId = request.getSession().getAttribute("LOGIN_NAME").toString();
			log.setOpuserId(userId);
			log.setReachTime(reqReachTime);
			log.setRespTime(DateToolkit.getNowString());
			oprLog.addOprLog(log);
		} catch (Exception e) {
			System.out.println("aop log error =========" + e);
		}
	}

	private String getLogContent(JoinPoint joinPoint, HttpServletRequest request) {
		String buss = joinPoint.getSignature().getName();
		buss = buss.substring(0, buss.lastIndexOf("_log"));
		String action = "";
		int pos = 3;
		if(buss.indexOf("add") == 0) {
			action = "添加了";
		} else if(buss.indexOf("mod") == 0) {
			action = "修改了";
		} else if(buss.indexOf("del") == 0) {
			action = "删除了";
		} else {
			action = "操作了";
			pos = 0;
		}
		buss = buss.substring(pos);
		String clsName = joinPoint.getTarget().getClass().getName();
		clsName = clsName.substring(clsName.lastIndexOf(".") + 1);
		StringBuilder sb = new StringBuilder("(");
		Iterator<Map.Entry<String, String[]>> it = request.getParameterMap().entrySet().iterator();
		boolean start = true;
		while (it.hasNext()) {
			if (!start) {
				sb.append(", ");
			}
			Map.Entry<String, String[]> e = it.next();
			sb.append(e.getKey()).append(":").append(e.getValue()[0]);
			start = false;
		}
		sb.append(")");
		return clsName + action + buss + sb.toString();
	}

	private HttpServletRequest getRequest(Object args[]) {
		for (Object arg : args) {
			if (arg instanceof HttpServletRequest) {
				return (HttpServletRequest) arg;
			}
		}
		return null;
	}

}
